package com.example.personalizededucationsystem.controller;

import com.example.personalizededucationsystem.dto.dto.DynamicQuestionRequestDto;
import com.example.personalizededucationsystem.dto.dto.DynamicQuestionResponseDto;
import com.example.personalizededucationsystem.dto.dto.UpdateUserRequestDto;
import com.example.personalizededucationsystem.dto.dto.UserDetailResponseDto;
import com.example.personalizededucationsystem.dto.request.KnowledgePointRequest;
import com.example.personalizededucationsystem.dto.request.QuestionRequest;
import com.example.personalizededucationsystem.model.KnowledgePoint;
import com.example.personalizededucationsystem.model.Question;
import com.example.personalizededucationsystem.model.User;
import com.example.personalizededucationsystem.service.AIAssistanceService;
import com.example.personalizededucationsystem.service.KnowledgeService;
import com.example.personalizededucationsystem.service.QuestionBankService;
import com.example.personalizededucationsystem.service.UserService;
import com.example.personalizededucationsystem.utils.ApprovalStatus;
import com.example.personalizededucationsystem.utils.IP_VALUE;
import com.example.personalizededucationsystem.utils.PagedResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@CrossOrigin(origins = IP_VALUE.IP)
@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    private final QuestionBankService questionBankService;
    private final UserService userService;
    private final KnowledgeService knowledgeService;
    private final AIAssistanceService aiAssistanceService;

    @Autowired
    public AdminController(QuestionBankService questionBankService, UserService userService, KnowledgeService knowledgeService, AIAssistanceService aiAssistanceService) {
        this.questionBankService = questionBankService;
        this.userService = userService;
        this.knowledgeService = knowledgeService;
        this.aiAssistanceService = aiAssistanceService;
    }

    /**
     * 知识点管理相关
     */

    @PostMapping("/create-knowledge-points")
    public ResponseEntity<KnowledgePoint> createKnowledgePoint(@RequestBody KnowledgePointRequest request) {
        KnowledgePoint createdKp = questionBankService.createKnowledgePoint(request);
        return new ResponseEntity<>(createdKp, HttpStatus.CREATED);
    }

    @GetMapping("/knowledge-points/APPROVED/{page}")
    public ResponseEntity<PagedResult<KnowledgePoint>> getKnowledgePoints(@PathVariable int page, @RequestParam(required = false) String keyword, @RequestParam String subject) {
        return ResponseEntity.ok(knowledgeService.getKnowledgePointsByStatusAndSubjects(ApprovalStatus.APPROVED, page, keyword, subject));
    }

    @GetMapping("/knowledge-points/{status}/{page}")
    public ResponseEntity<PagedResult<KnowledgePoint>> getKnowledgePointsByStatus(@PathVariable String status, @PathVariable int page, @RequestParam(required = false) String keyword) {
        ApprovalStatus kpStatus = ApprovalStatus.valueOf(status);
        return ResponseEntity.ok(knowledgeService.getKnowledgePointsByStatus(kpStatus, page, keyword));
    }

    @PutMapping("/knowledge-points/{id}/approve")
    public ResponseEntity<Boolean> approveKnowledgePoint(@PathVariable Long id) {
        return ResponseEntity.ok(knowledgeService.approveKnowledgePoint(id));
    }

    @PutMapping("/knowledge-points/{id}/reject")
    public ResponseEntity<Boolean> rejectKnowledgePoint(@PathVariable Long id) {
        return ResponseEntity.ok(knowledgeService.rejectKnowledgePoint(id));
    }

    /**
     * 问题管理相关
     */

    @PostMapping("/questions")
    public ResponseEntity<Question> createQuestion(@RequestBody QuestionRequest request, @AuthenticationPrincipal User currentUser) {
        Question createdQuestion = questionBankService.createQuestion(request, currentUser);
        return new ResponseEntity<>(createdQuestion, HttpStatus.CREATED);
    }

    @GetMapping("/questions/{id}")
    public ResponseEntity<Question> findQuestion(@PathVariable Long id) {
        return ResponseEntity.ok(questionBankService.getAccurateQuestion(id));
    }

    @PutMapping("/questions/{id}/approve")
    public ResponseEntity<Boolean> approveQuestion(@PathVariable Long id) {
        return ResponseEntity.ok(questionBankService.approveQuestion(id));
    }

    @PutMapping("/questions/{id}/reject")
    public ResponseEntity<Boolean> rejectQuestion(@PathVariable Long id) {
        return ResponseEntity.ok(questionBankService.rejectQuestion(id));
    }

    @GetMapping("/approved-questions/{page}")
    public ResponseEntity<PagedResult<Question>> getApprovedQuestions(@PathVariable int page, @RequestParam(required = false) String keyword, @RequestParam(required = false) String subject) {
        return ResponseEntity.ok(questionBankService.getApprovedQuestions(page, keyword, subject));
    }

    @GetMapping("/pending-questions/{page}")
    public ResponseEntity<PagedResult<Question>> getPendingQuestions(@PathVariable int page, @RequestParam(required = false) String keyword, @RequestParam(required = false) String subject) {
        return ResponseEntity.ok(questionBankService.getPendingQuestions(page, keyword, subject));
    }

    /**
     * 用户管理相关
     */

    @GetMapping("/users")
    public ResponseEntity<List<UserDetailResponseDto>> getAllUsers() {
        List<UserDetailResponseDto> users = userService.findAllUsers();
        return ResponseEntity.ok(users);
    }

    @GetMapping("/users/{userId}")
    public ResponseEntity<UserDetailResponseDto> getUserById(@PathVariable Long userId) {
        User user = userService.findUserById(userId);
        return ResponseEntity.ok(UserDetailResponseDto.fromEntity(user));
    }

    @PutMapping("/users/{userId}")
    public ResponseEntity<UserDetailResponseDto> updateUser(@PathVariable Long userId, @RequestBody UpdateUserRequestDto request) {
        User updatedUser = userService.updateUser(userId, request);
        return ResponseEntity.ok(UserDetailResponseDto.fromEntity(updatedUser));
    }

    @PostMapping("/questions/generate")
    public ResponseEntity<DynamicQuestionResponseDto> generateQuestion(@RequestBody DynamicQuestionRequestDto request) {
        DynamicQuestionResponseDto response = aiAssistanceService.generateQuestionFromAI(request.knowledge_point_name(), request.subject(), request.question_type(), request.difficulty());
        if (response == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.ok(response);
    }
}
